package org.hackystat.app.projectstatus.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.hackystat.app.projectstatus.data.ProjectStatusHTMLMailer;
import org.hackystat.app.projectstatus.timer.ProjectStatusTimerTask;
import org.hackystat.core.common.project.Project;
import org.hackystat.core.common.project.ProjectManager;
import org.hackystat.core.kernel.mvc.CommandRequest;
import org.hackystat.core.kernel.mvc.Page;
import org.hackystat.core.kernel.timer.DailyTimer;
import org.hackystat.core.kernel.timer.TimerTaskManager;
import org.hackystat.core.kernel.user.User;
import org.hackystat.core.kernel.util.Day;

/**
 * Implements the Project Status alert command request which displays the current set of Project
 * instances associated with this user along with checkboxes indicating whether the user desires a
 * daily email with that Project's status.
 * <p>
 * Uses the following JSP Selectors:
 * <ul>
 * <li> ProjectStatusSelector
 * </ul>
 * <p>
 * Forwards back to the Alerts page for display of the updated value. Populates the request with the
 * following attributes:
 * <ul>
 * <li>ProjectStatusFeedback: an indication that the update occurred.
 * </ul>
 * 
 * @author Josh Stupplebeen
 * 
 */
public class AlertEmailManager implements CommandRequest {

  /** List of email address strings. */
  private List<String> addrs = new ArrayList<String>();

  /** Map of a project to its enabled status. ie. "Project" -> "enabled". */
  private static Map<Project, String> projectEnabled = new HashMap<Project, String>();

  /**
   * Map of a project name to the list of emails which will be recieving emails.
   */
  private Map<Project, List<String>> projectEmails = new HashMap<Project, List<String>>();

  /** The key string used to store/retrieve this alert from the User instance. */
  public static final String PROJECTSTATUSPROP_KEY = "alert.ProjectStatus";

  private Day day = Day.getInstance(2007, 1, 8);

  /**
   * The process method for this command.
   * 
   * @param request The request object.
   * @param user The user who made this request.
   * @return The Preferences page or Error page.
   */
  public Page process(HttpServletRequest request, User user) {

    // Add the DailyEmailAlert task to the Daily Timer.
    TimerTaskManager timerTaskManager = DailyTimer.getInstance().getTimerTaskManager();
    if (!timerTaskManager.hasTimerTask(ProjectStatusTimerTask.class.getName())) {
      DailyTimer.getInstance().getTimerTaskManager().addTask(new ProjectStatusTimerTask());
    }

    ProjectManager manager = ProjectManager.getInstance();
    Set<Project> projectSet = manager.getProjectsWithOwner(user);

    List<String> feedbackList = new ArrayList<String>();
    AlertEmailManagerUpdate emailUpdater = new AlertEmailManagerUpdate();
    ProjectStatusHTMLMailer emailManager = new ProjectStatusHTMLMailer();

    Page page = new Page("/AlertManager.jsp", "The Alert Manager");
    request.setAttribute("ProjectsOwned", projectSet);

    int x = 0;
    String enabled;
    String attribute;

    for (Project project : projectSet) {
      enabled = request.getParameter("ProjectStatus");
      System.out.println(" ** Parameter Value = " + enabled);
      if ("enabled".equals(enabled)) {
        AlertEmailManager.projectEnabled.put(project, "enabled");
      }
      else {
        AlertEmailManager.projectEnabled.put(project, "disabled");
      }
      x++;
    }
//    
//    System.out.println(" -- State of the Enabled Map --");
//    Iterator i = AlertEmailManager.projectEnabled.entrySet().iterator();
//    while (i.hasNext()) {
//      Map.Entry pairs = (Map.Entry) i.next();
//      System.out.println(pairs.getKey() + " = " + pairs.getValue());
//      Project p = (Project) pairs.getKey();
//      System.out.println(" -- " + p.getName() + " status: "
//          + AlertEmailManager.projectEnabled.get(p));
//    }

    this.projectEmails = emailUpdater.getEmailMap();

    boolean mailSent = false;
    //
    // for (Project project : projectSet) {
    // this.addrs = this.projectEmails.get(project);
    // try {
    // mailSent = emailManager.processHTMLMail(request, user, this.addrs, project, day);
    // }
    // catch (Exception e) {
    // request.setAttribute(Controller.EXCEPTION_ATTRIBUTE, e);
    // return page;
    // }
    // }
    request.setAttribute("ProjectStatusFeedback", "Project Alert Status Updated");

    return page;
  }

  /**
   * Returns a List of the project names which emails need to be generated.
   * 
   * @return A list of the projects that are enabled.
   * @param user The user logged in.
   */
  public List<String> getProjectEnabledStatus(User user) {
    List<String> enabledProjects = new ArrayList<String>();
    ProjectManager manager = ProjectManager.getInstance();
    Set<Project> projectSet = manager.getProjectsWithOwner(user);
    for (Project project : projectSet) {
      if ("enabled".equals(projectEnabled.get(project.getName()))) {
        // do nothing
      }
    }
    return enabledProjects;
  }

  /**
   * Sets the alert to enabled/disabled according to the state of the checkbox in the file
   * AlertManager.jsp.
   * 
   * @param enableMap A mapping of the project the user owns to their enabled status.
   * 
   */
  public static void setEnableMap(Map<Project, String> enableMap) {
    AlertEmailManager.projectEnabled = enableMap;
  }


  /**
   * Test method for what value is being retrieved from the jsp page.
   * 
   * @param user
   * @param project
   * @param enable
   */
  public static void checkEnableStatus(User user, Project project, String enable, String jstlVar) {
//    System.out.println(" -- Checking enable string --");
//    System.out.println("User:     " + user.getUserEmail());
//    System.out.println("Project:  " + project.getName());
//    System.out.println("Enable:   " + enable);
//    System.out.println("JSTL Var: " + jstlVar + "\n");
  }
  
  /**
   * Retrieves the alert status and sets the checkbox on the jsp page to checked/unchecked according
   * to the specific project's alert status.
   * 
   * @param user The User.
   * @return Returns a boolean according to whether the alert is enabled.
   */
  public static boolean isEnabled(User user) {
    return true;
  }
  
  /**
   * Sets the enabled status for the associated project.
   * 
   * @param user The user.
   * @param enabled The enabled/disabled status for this project.
   * @param project The project.
   */
  public static void setEnabled(User user, Project project, boolean enabled) {
    System.out.println(" -- Project Status Enable Results --");
    System.out.println("Project: " + project.getName());
    if (enabled) {
      System.out.println("Alert Status: enabled");
    }
    else {
      System.out.println("Alert Status: disabled");
    }
    user.put("projectstatus." + project.getName(), enabled  ? "enabled" : "disabled");
  }
}
